<script lang="ts" setup>
import { onMounted, ref, onUnmounted } from 'vue';
import { useThrottleFn } from '@vueuse/core'

const MAX_SCROLL = 500
const opacity = ref(0)
const isVisible = ref(true)

const toTop = () => {
  const time = setInterval(() => {
    if (document.documentElement.scrollTop <= 0) {
      clearInterval(time)
    }
    document.documentElement.scrollTop -= 100
  }, 1)
}

const opactiyChange = () => {
  opacity.value = (document.documentElement.scrollTop / MAX_SCROLL >= 1) ? 1 : document.documentElement.scrollTop / MAX_SCROLL
  isVisible.value = document.documentElement.scrollTop > 0
}

const throttleFn = useThrottleFn(opactiyChange, 10)

onMounted(() => {
  document.addEventListener('scroll', throttleFn)
})

onUnmounted(() => {
  document.removeEventListener('scroll', throttleFn)
})
</script>

<template>
  <div class="relative right--60px mx-auto flex justify-right container">
    <div v-if="isVisible" class="top-button fixed bottom-240px z-999 size-48 flex-center cursor-pointer border-1 border-hex-fff rounded-4 border-solid bg-[linear-gradient(180deg,#F7F7F7_0%,#FFFFFF_100%)] shadow-[0_1px_6px_0_rgba(0,0,0,0.04)]" @click="toTop">
      <div class="i-icons:to-top size-20 text-hex-3D7CFA"></div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.top-button {
  background: #fff 0.08;
  opacity: v-bind("opacity");
  transition: all 0.5s linear;

  &:hover {
    background: #fff 1;
  }
}
</style>
